import { GlobEnvConfig } from "#/config";
import { API_ADDRESS } from "@/enums/cacheEnum";

const getVariableName = (title: string) => {
  function strToHex(str: string) {
    const result: string[] = [];
    for (let i = 0; i < str.length; i++) {
      // charCodeAt 检索字符串中特定位置的字符的Unicode 值 ,参数为字符的索引。不为整将被转换为整数——undefined 被转换为 0。
      //toString 内的参数为进制
      const hex = str.charCodeAt(i).toString(16);

      // slice(-4)  保留后四位
      result.push(("000" + hex).slice(-4));
    }
    return result.join("").toUpperCase();
  }

  //  \s 匹配一个空白字符，包括空格、制表符、换页符和换行符
  return `__PRODUCTION__${strToHex(title) || "__APP"}__CONF__`
    .toUpperCase()
    .replace(/\s/g, "");
};

// 获取环境配置
export function getAppEnvConfig() {
  const ENV_NAME = getVariableName(import.meta.env.VITE_APP_TITLE);

  //import.meta.env.DEV: {boolean} 应用是否运行在开发环境 (永远与 import.meta.env.PROD相反)。
  const ENV = import.meta.env.DEV
    ? (import.meta.env as unknown as GlobEnvConfig)
    : (window[ENV_NAME] as unknown as GlobEnvConfig);

  const {
    VITE_GLOB_APP_TITLE,
    VITE_GLOB_API_URL_PREFIX,
    VITE_GLOB_UPLOAD_URL,
  } = ENV;

  let { VITE_GLOB_API_URL } = ENV;

  if (localStorage.getItem(API_ADDRESS)) {
    const address = JSON.parse(localStorage.getItem(API_ADDRESS) || "{}");
    if (address && address.key) {
      VITE_GLOB_API_URL = address.val;
    }
  }

  return {
    VITE_GLOB_APP_TITLE,
    VITE_GLOB_API_URL,
    VITE_GLOB_API_URL_PREFIX,
    VITE_GLOB_UPLOAD_URL,
  };
}
